<template>
  <!-- 自有资金来源 -->
  <div style="width:33%;float:left">
  <a-table bordered :data-source="dataSource1" :columns="columns" :pagination="false" >
    <template #bodyCell="{ column, text, record ,index}">
      <template v-if="column.dataIndex === 'paravalue'">
        <div class="editable-cell">
          <div v-if="editableData1[record.key]" class="editable-cell-input-wrapper">
            <a-input v-model:value="editableData1[record.key].paravalue" @pressEnter="save1(record.key)" />
            <check-outlined class="editable-cell-icon-check" @click="save1(record.key)" />
          </div>
          <div v-else class="editable-cell-text-wrapper">
            <!-- 把key=1的持股比例的输入框给取消掉 v-if="record.key !=='1'"-->
            <!-- <div v-if="record.key !=='1'"> -->
              {{ text || ' ' }}
              <edit-outlined class="editable-cell-icon" @click="edit1(record.key)" /> 
            <!-- </div> -->
          </div>
        </div>
      </template>
    </template>
    <template #title>自有资金来源</template>
    <!-- <template #footer>页脚</template> -->
  </a-table>
  </div>
  <!--融资资金来源-->
  <div style="width:33%;float:left">
  <a-table bordered :data-source="dataSource2" :columns="columns" :pagination="false" >
    <template #bodyCell="{ column, text, record ,index}">
      <template v-if="column.dataIndex === 'paravalue'">
        <div class="editable-cell">
          <div v-if="record.paraname === '还本付息方式'">
              <a-select
                ref="select"
                v-model:value="selectValue1"
                default-value="1"
                style="width: 100%"
                :options="options1"
                @focus="focus1"
                @change="(value:any,option:any) => handleChange1(value,option,record.key)"
               
              ></a-select>
          </div>
          <div v-else>
                <div v-if="editableData2[record.key]" class="editable-cell-input-wrapper">
                  <a-input v-model:value="editableData2[record.key].paravalue" @pressEnter="save2(record.key)" />
                  <check-outlined class="editable-cell-icon-check" @click="save2(record.key)" />
                </div>
                <div v-else class="editable-cell-text-wrapper">
                  <!-- 屏蔽贷款银行列表的输入框 -->
                  <!-- <div v-if="record.key!=='1'"> -->
                  {{ text || ' ' }}
                  <edit-outlined class="editable-cell-icon" @click="edit2(record.key)" />
                  <!-- </div> -->
                </div>
          </div>

        </div>
      </template>
    </template>
    <template #title>融资资金来源</template>
    <!-- <template #footer>页脚</template> -->
  </a-table>
  </div>
    <!--滚动资金及短期贷款-->
  <div style="width:33%;float:right">
  <a-table bordered :data-source="dataSource3" :columns="columns" :pagination="false" >
    <template #bodyCell="{ column, text, record ,index}">
      <template v-if="column.dataIndex === 'paravalue'">
        <div class="editable-cell">
          <!-- 若是第一行，则使用复选框 selectValue2是默认选项-->
          <div v-if="record.key==='0'">
              <a-select
                ref="select"
                v-model:value="selectValue2"
                style="width: 100%"
                :options="options2"
                @focus="focus2"
                @change="(value:string,option:any)=>handleChange2(value,option,record.key)"
              ></a-select>
          </div>
          <div v-else>
            <div v-if="editableData3[record.key]" class="editable-cell-input-wrapper">
              <a-input v-model:value="editableData3[record.key].paravalue" @pressEnter="save3(record.key)" />
              <check-outlined class="editable-cell-icon-check" @click="save3(record.key)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              {{ text || ' ' }}
              <edit-outlined class="editable-cell-icon" @click="edit3(record.key)" />
            </div>
          </div>
        </div>
      </template>
    </template>
    <template #title>滚动资金及短期贷款</template>
    <!-- <template #footer>页脚</template> -->
  </a-table>
  </div>
</template>


<script lang="ts">

import { computed, defineComponent, reactive, ref } from 'vue';
import type { Ref, UnwrapRef } from 'vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';
import type { SelectProps } from 'ant-design-vue'
interface DataItem {
  key: string;
  paraname: string;
  paravalue: string;
  children?: DataItem[];   //加载子数据项
}


export default defineComponent({
  components: {
    CheckOutlined,
    EditOutlined,
  },
  setup() {
    const columns = [
      {
        title: '参数名',  //合并跨度两列
        dataIndex: 'paraname',
        width: '50%',
      },
      {
        title: '参数值',
        dataIndex: 'paravalue',
      },
      // {
      //   title: '操作',
      //   dataIndex: 'operation',
      // },
    ];

    ////////////////////--------------公共方法--------start-------------------

    //点击编辑按钮后，显示输入框.some，every,foreach退出循环的区别
    const displayInput=(key:string,datasource:Ref<DataItem[]>,temp_editableData:UnwrapRef<Record<string, DataItem>>) => {
        datasource.value.some(item =>{
           if(key===item.key) {temp_editableData[key]=cloneDeep(item)}
           if(key!==item.key && item.children) displayInput(key,ref(item.children),temp_editableData)
        })
    }
    //点击保存按钮后，改变datasource的值
    const saveItem = (key:string,datasource:Ref<DataItem[]>,temp_editableData:UnwrapRef<Record<string, DataItem>>) => {
        datasource.value.some(item => {
          //some里的item传不出去//return会结束此次循环，进行下一次循环
          if(item.key === key) { Object.assign(item, temp_editableData[key]) ; return true } 
          if(item.key !== key && item.children) saveItem(key,ref(item.children),temp_editableData)
        })
    }
    //找到所有祖先节点的位置。以便添加新列
    //js递归some函数，最然里层的some循环停止，但外层循坏并没有停止
    const findfatherkey =(flag:boolean,childkey:string,fathers_key:string,datasource:Ref<DataItem[]>) =>{
      datasource.value.some(item =>{
        if(flag) return true  //若已找到父节点，停止本层some遍历
        if(item.key === childkey){ flag=true; return true } 
        if(item.key !== childkey && item.children) {
          var obj=findfatherkey(flag,childkey,item.key,ref(item.children))
          fathers_key=obj.fathers_key
          flag=obj.flag
        }})
      return {fathers_key:fathers_key,flag:flag}
    }

    //查找mykey的所有祖先节点
    const getParents:any=(flag:boolean,datasource: Ref<DataItem[]>, mykey: string,parentkeys:Array<string>) =>{
      datasource.value.some(item=>{
        if(flag) return true
        if(item.key === mykey) { flag=true; return true}  //parentkeys.push(item.key);添加mykey节点
        if(item.key !== mykey && item.children){
          var obj=getParents(flag,ref(item.children),mykey,parentkeys)    //
          parentkeys=obj.parentkeys
          flag=obj.flag
          if(flag) parentkeys.push(item.key)   //确认是父节点才添加
        }
      })

      return {parentkeys:parentkeys,flag:flag}
    }

    //寻找父节点的dataItem项，并且定位该项在dataSource的位置。

    ////////////////////--------------公共方法---------end--------------------
    //自有资金来源-----start---------------------------------------------------------------------------------
    const dataSource1: Ref<DataItem[]> = ref([
      {
        key: '0',
        paraname: '合资企业个数',
        paravalue: '2',
      },
      {
        key: '1',
        paraname: '股份比例(%) ',   
        paravalue: '',
        children:[       ///childrent项的个数是根据合资企业个数来动态生成的.从js里载入数据源，把投资方那一列给按需动态生成
            {
                key:'5',
                paraname: '投资方1',
                paravalue: '40',
            },
            {
                key:'8',
                paraname: '投资方2',
                paravalue: '60',
            },
        ],
      },
     ]);
    const count1 = computed(() => dataSource1.value.length + 1);
    const editableData1: UnwrapRef<Record<string, DataItem>> = reactive({}); //暂时存储dataItem数据项
    
    //编辑
    const edit1 = (key: string) => {
      displayInput(key,dataSource1,editableData1)
    }
    //保存
    const save1 = (key: string) => {
      saveItem(key,dataSource1,editableData1)
      delete editableData1[key];
    };
    //自有资金来源------end-----------------------------------------------------------------------------------------


    //融资资金来源-----start---------------------------------------------------------------------------------------
    const dataSource2: Ref<DataItem[]> = ref([
      {
        key: '0',
        paraname: '贷款银行个数',
        paravalue: '2'
      },
      {
        key: '1',
        paraname: '贷款银行列表',
        paravalue: '',
        children:[
          {
            key: '2',
            paraname: '银行1',    //跨4行怎么做？
            paravalue: '',
            children:[{
                key: '3',
                paraname: '融资比例(%)',    //跨4行怎么做？
                paravalue: '45',
            },
            {
                key: '4',
                paraname: '预定还款期(年)',    //跨4行怎么做？
                paravalue: '15'
            },
            {
                key: '5',
                paraname: '宽限期(年)',    //跨4行怎么做？
                paravalue: '1'
            },
            {
                key: '6',
                paraname: '计息次数',    //跨4行怎么做？
                paravalue: '1'
            },
            {
                key: '7',
                paraname: '还本付息方式',  
                paravalue: '这里是选择框'
            },  
            {
                key: '8',
                paraname: '长期贷款利率(%)',    //跨4行怎么做？
                paravalue: '',
                children:[{
                  key: '9',
                  paraname: '第一年',
                  paravalue: '4.9'
                },            {
                  key: '10',
                  paraname: '第二年',
                  paravalue: '4.9'
                },            {
                  key: '11',
                  paraname: '第三年',
                  paravalue: '4.9'
                },             {
                  key: '12',
                  paraname: '第四年',
                  paravalue: '4.9'
                },              {
                  key: '13',
                  paraname: '第五年',
                  paravalue: '4.9'
                },              {
                  key: '14',
                  paraname: '第六年',
                  paravalue: '4.9'
                },              {
                  key: '15',
                  paraname: '第七年',
                  paravalue: '4.9'
                },              {
                  key: '16',
                  paraname: '第八年',
                  paravalue: '4.9'
                },              {
                  key: '17',
                  paraname: '第九年',
                  paravalue: '4.9'
                },              {
                  key: '18',
                  paraname: '第十年',
                  paravalue: '4.9'
                },              {
                  key: '19',
                  paraname: '第十一年',
                  paravalue: '4.9'
                },              {
                  key: '20',
                  paraname: '第十二年',
                  paravalue: '4.9'
                }         
                ]
            },      
            ]
          },
          {
            key: '21',
            paraname: '银行2',    //跨4行怎么做？
            paravalue: '',
            children:[{
                key: '22',
                paraname: '融资比例(%)',    //跨4行怎么做？
                paravalue: '55',
            },
            {
                key: '23',
                paraname: '预定还款期(年)',    //跨4行怎么做？
                paravalue: '15'
            },
            {
                key: '24',
                paraname: '宽限期(年)',    //跨4行怎么做？
                paravalue: '1'
            },
            {
                key: '25',
                paraname: '计息次数',    //跨4行怎么做？
                paravalue: '1'
            },
            {
                key: '26',
                paraname: '还本付息方式',    //跨4行怎么做？
                paravalue: '等额还本利息照付/这里是选择框'
            },  
            {
                key: '27',
                paraname: '长期贷款利率(%)',    //跨4行怎么做？
                paravalue: '',
                children:[
                  {
                    key: '28',
                    paraname: '第一年',
                    paravalue: '4.9'
                  },            {
                    key: '29',
                    paraname: '第二年',
                    paravalue: '4.9'
                  },            {
                    key: '30',
                    paraname: '第三年',
                    paravalue: '4.9'
                  },             {
                    key: '31',
                    paraname: '第四年',
                    paravalue: '4.9'
                  },              {
                    key: '32',
                    paraname: '第五年',
                    paravalue: '4.9'
                  },              {
                    key: '33',
                    paraname: '第六年',
                    paravalue: '4.9'
                  },              {
                    key: '34',
                    paraname: '第七年',
                    paravalue: '4.9'
                  },              {
                    key: '35',
                    paraname: '第八年',
                    paravalue: '4.9'
                  },              {
                    key: '36',
                    paraname: '第九年',
                    paravalue: '4.9'
                  },              {
                    key: '37',
                    paraname: '第十年',
                    paravalue: '4.9'
                  },              {
                    key: '38',
                    paraname: '第十一年',
                    paravalue: '4.9'
                  },              {
                    key: '39',
                    paraname: '第十二年',
                    paravalue: '4.9'
                  }         
                ]
            },      
            ]
          },
        ]
      },
     ]);
   //点击约定还款时添加的列表
    const dataSource2_add: Ref<DataItem> = ref({  
        key: '40',  //key值动态递增
        paraname: '还款金额(万元)',
        paravalue: '',
        children:[
          {
            key: '41',
            paraname: '第一年',
            paravalue: '4'
          },            {
            key: '42',
            paraname: '第二年',
            paravalue: '4'
          },            {
            key: '43',
            paraname: '第三年',
            paravalue: '4'
          },             {
            key: '44',
            paraname: '第四年',
            paravalue: '9'
          },              {
            key: '45',
            paraname: '第五年',
            paravalue: '9'
          },              {
            key: '46',
            paraname: '第六年',
            paravalue: '9'
          },              {
            key: '47',
            paraname: '第七年',
            paravalue: '9'
          },              {
            key: '48',
            paraname: '第八年',
            paravalue: '9'
          },              {
            key: '49',
            paraname: '第九年',
            paravalue: '9'
          },              {
            key: '50',
            paraname: '第十年',
            paravalue: '9'
          },              {
            key: '51',
            paraname: '第十一年',
            paravalue: '9'
          },              {
            key: '52',
            paraname: '第十二年',
            paravalue: '9'
          } 
        ] 
        })

    const count2 = computed(() => dataSource2.value.length + 1);
    const editableData2: UnwrapRef<Record<string, DataItem>> = reactive({});

    const edit2 = (key: string) => {
      displayInput(key,dataSource2,editableData2)
      // editableData2[key] = cloneDeep(dataSource2.value.filter(item => key === item.key)[0]);
    };
    const save2 = (key: string) => {
      saveItem(key,dataSource2,editableData2)
      delete editableData2[key];
    };
    //融资资金来源------end----------------------------------------------------------------------------------------

    //滚动资金及短期贷款----start-----------------------------------------------------------------------------------
    const dataSource3: Ref<DataItem[]> = ref([
      {
        key: '0',
        paraname: '流动资金计算方式',
        paravalue: '单位千瓦指标/选项框'
      },
      {
        key: '1',
        paraname: '单位千瓦指标(元/kw) ',   
        paravalue: '30',
      },
      {
        key: '2',
        paraname: '自有流动资金比例(%) ',   
        paravalue: '30',
      },
      {
        key: '3',
        paraname: '流动资金贷款利率(%) ',   
        paravalue: '4.35',
      },
      {
        key: '4',
        paraname: '短期贷款利率(%) ',   
        paravalue: '4.35',
      },
     ]);
    const count3 = computed(() => dataSource3.value.length + 1);
    const editableData3: UnwrapRef<Record<string, DataItem>> = reactive({}); //暂时存储dataItem数据项

    const edit3 = (key: string) => {
      displayInput(key,dataSource3,editableData3)
    };
    const save3 = (key: string) => {
      saveItem(key,dataSource3,editableData3)
      delete editableData3[key];
    };
    //滚动资金及短期贷款------end--------------------------------------------------------------------------------

    //下拉列表----start-------------------------------------------------------------------------------------
    const options1 = ref<SelectProps['options']>([
      {
        value: '等额还本付息',
        label: '等额还本付息',
      },
      {
        value: '等额还本利息照付',
        label: '等额还本利息照付',
      },
      {
        value: '约定还款',
        label: '约定还款',
      },
    ]);
    const options2 = ref<SelectProps['options']>([
      {
        value: '单位千瓦指标',
        label: '单位千瓦指标',
      },
      {
        value: '手动输入流动资金',
        label: '手动输入流动资金',
      },
    ]);
    const focus1 = () => {
      console.log('focus1');
    };
    const focus2 = () => {
      console.log('focus2');
    };
    const handleChange1 = (value: string,option:any,key:string) => {
      //选项改变时不需要触发什么函数
      console.log('开始')
      const parentkeys=getParents(false,dataSource2,key,[]).parentkeys
      console.log(parentkeys)
      if(value==="约定还款"){  //添加一列
        // dataSource2.value.push(dataSource2_add.value)
        addRefundList(parentkeys[0],dataSource2)
      }
    };

    const addRefundList=(directparentkey:string,datasource: Ref<DataItem[]>) => {
      datasource.value.some(item=>{
        console.log("遍历顺序："+item.key)
        if(item.key === directparentkey) { item.children?.push(dataSource2_add.value) ;return true }
        if(item.key !== directparentkey&& item.children) addRefundList(directparentkey, ref(item.children))
      })
    }

    const handleChange2 = (value: string,option:any,key:string) => {
      //选项改变时不需要触发什么函数
      console.log(`selected ${value}`);
      dataSource3.value.some(item=>{
        if(value==="单位千瓦指标" && item.paraname==="流动资金(万元)") {item.paraname="单位千瓦指标(元/kw)";item.paravalue="30";return true}  //Object.assign(item,source)
        if(value==="手动输入流动资金" && item.paraname==="单位千瓦指标(元/kw)") {item.paraname="流动资金(万元)";item.paravalue="20";return true}
      })
    };


    //下拉列表----end---------------------------------------------------------------------------



    return{
        columns,
        dataSource1,
        dataSource2,
        dataSource3,
        count1,
        count2,
        count3,
        editableData1,
        editableData2,
        editableData3,
        edit1,
        edit2,
        edit3,
        save1,
        save2,
        save3,
        //设置默认选项  ////////////////////////////////////////////

        //点击约定还款时还会添加一列

        ///////////////////////////////////////
        options1,
        focus1,
        handleChange1,
        selectValue1:ref('等额还本利息照付'),
        options2,
        focus2,
        handleChange2,
        selectValue2:ref('单位千瓦指标'),

    };
  },


})



</script>
<style lang="less">
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}
.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>